/**
 * UserQueue Controller层
 */
app.controller('usrQueueCtrl',function($scope, usrQueueService) {
    var nameForSearch = '';
    var msgBox = null;
    var rgQueueName = "^Q[.]U[_][0-9A-Z_]+$";
    //页面初始化加载
    usrQueueService.findUserQueueByName({
        action : 'findUserQueueByName',
        currentPage : 1,
        pageSize : 10
    }, function(data){
        //展示数据
        if(data.state == 'SUCCESS'){
            $scope.queues = data.data.queueVO;
            pageOperation($scope,data.pageInfo);
        }else{
            if(msgBox == null) {
                bootbox.alert(data.reason, function() {
                    msgBox == null
                });
            }

        }
    });

    //查询按钮查询
    $scope.findByConditions = function(){
        $scope.pageSize = $scope.selectPageSize;
        nameForSearch = $scope.searchName;
        usrQueueService.findUserQueueByName({
            action : 'findUserQueueByName',
            name : $scope.searchName,
            currentPage : 1,
            pageSize : $scope.pageSize
        },function(data){
            if(data.state == 'SUCCESS'){
                $scope.queues = data.data.queueVO;
                pageOperation($scope,data.pageInfo);
            }else{
                bootbox.alert("查询失败(" + data.reason + ")");
            }
        });
    }

    //通过分页按钮查询
    $scope.findByCondition = function(){
        $scope.pageSize = $scope.selectPageSize;
        usrQueueService.findUserQueueByName({
            action : 'findUserQueueByName',
            name : nameForSearch,
            currentPage : $scope.selPage,
            pageSize : $scope.pageSize
        },function(data){
            if(data.state == 'SUCCESS'){
                $scope.queues = data.data.queueVO;
                pageOperation($scope,data.pageInfo);
            }else{
                bootbox.alert("查询失败(" + data.reason + ")");
            }
        });
    }

    /**
     * 初始化队列对话框
     */
    function initQueueDialog(){
       $scope.frmQueue.name.$setValidity("enable",true);
       $scope.frmQueue.name.$setValidity("length",true);
       $scope.frmQueue.name.$setValidity("pattern",true);
       $scope.frmQueue.name.$setValidity("unique",true);
    }

    /**
     * 新增用户队列
     */
    $scope.createQueue = function(){
        $('#dialogQueue').on('show.bs.modal',function(){
            initQueueDialog();
            $('#name').attr('disabled',false);
            $scope.title = '新增用户队列';
            $scope.queue.id = 0;
            $scope.queue.name = '';
            $scope.queue.priority = '0';
            $scope.queue.persistent = '0';
            $scope.queue.maxDepth = 5000;
            $scope.queue.maxMsgLength = 4194304;
            $scope.queue.retainInterval = 999999999;
        });
        $('#dialogQueue').modal('show');
    }

    /**
     * 修改用户队列
     * @param queue
     */
    $scope.updateQueue = function(queue){
        var persistent = queue.persistent ? '1' : '0';
        var enable = queue.enable ? '1' : '0';
        $('#dialogQueue').on('show.bs.modal',function(){
            initQueueDialog();
            $('#name').attr('disabled',true);
            if(enable == '1'){
                $scope.frmQueue.name.$setValidity("enable",false);
            }
            $scope.title = '修改用户队列';
            $scope.queue.id = queue.id;
            $scope.queue.name = queue.name;
            $scope.queue.priority = queue.priority.toString();
            $scope.queue.persistent = persistent;
            $scope.queue.maxDepth = queue.maxDepth;
            $scope.queue.maxMsgLength = queue.maxMsgLength;
            $scope.queue.retainInterval = queue.retainInterval;
        });
        $('#dialogQueue').modal('show');
    }

    /**
     * 校验队列名称长度
     */
    $scope.checkQueueNameLength = function(queueName){
        if($scope.title == '新增用户队列'){
            if(queueName.length > 48){
                $scope.frmQueue.name.$setValidity("length",false);
            }else{
                $scope.frmQueue.name.$setValidity("length",true);
            }
        }
    }

    /**
    * 校验队列名称
    */
    $scope.checkQueueName = function(queueName){
        if($scope.title == '新增用户队列'){
            if(!queueName.match(rgQueueName)){
                $scope.frmQueue.name.$setValidity("pattern",false);
                return;
            }else{
                $scope.frmQueue.name.$setValidity("pattern",true);
            }
            usrQueueService.checkQueueName({
                action : 'checkQueueName',
                queueName : queueName
            },function(data) {
                if(data.state != 'SUCCESS'){
                    if(data.code == 0){
                        $scope.frmQueue.name.$setValidity("unique",false);
                        bootbox.alert(data.reason);
                    }
                }else{
                    $scope.frmQueue.name.$setValidity("unique",true);
                }
            });
        }
    }

    /**
     * 保存用户队列
     * @param queue
     * @param valid
     */
    $scope.save = function(queue){
        if(queue.id == 0){
            usrQueueService.save({
                id: queue.id,
                name: queue.name,
                type: 1,
                priority: queue.priority,
                persistent: queue.persistent,
                maxDepth: queue.maxDepth,
                maxMsgLength: queue.maxMsgLength,
                retainInterval: queue.retainInterval
            },{},function(data) {
                if(data.state == 'SUCCESS'){
                    $("#dialogQueue").modal("hide");
                    bootbox.alert("保存成功",function(){
                        $scope.cancel();
                        $scope.findByConditions();
                    });
                }else{
                    bootbox.alert("保存失败(" + data.reason + ")");
                }
            }, $scope.requestError);
        }else{
            var persistent = false;
            if(queue.persistent == '1'){
                persistent = true;
            }
            var persistent = 'true';
            var maxDepth = queue.maxDepth;
            var maxMsgLength =  queue.maxMsgLength;
            var retainInterval = queue.retainInterval;
            usrQueueService.updateQueue({
                id:queue.id,
                name:queue.name,
                type:1,
                priority:queue.priority,
                persistent:persistent,
                maxDepth:maxDepth,
                maxMsgLength:maxMsgLength,
                retainInterval:retainInterval
            },function(data){
               if(data.state == 'SUCCESS'){
                   $("#dialogQueue").modal("hide");
                   bootbox.alert("保存成功",function(){
                       $scope.cancel();
                       $scope.findByConditions();
                   });
               }else{
                   bootbox.alert("保存失败(" + data.reason + ")");
               }
            });
        }
    }

    /**
     * 删除用户队列
     * @param queue
     */
    $scope.deleteQueue = function(queue){
        if (!queue.enable) {
            bootbox.confirm({
                title: "系统提示",
                message: "确认是否要删除该队列？",
                buttons: {
                    cancel: {
                        className: 'btn-sm',
                        label: '<i class="glyphicon glyphicon-remove"></i> 取消'
                    },
                    confirm: {
                        className: 'btn-sm btn-success',
                        label: '<i class="glyphicon glyphicon-ok"></i> 确定'
                    }
                },
                callback: function (result) {
                    if(result) {
                        usrQueueService.delete({
                            id: queue.id
                        }, function (data) {
                            if (data.state == 'SUCCESS') {
                                bootbox.alert("删除成功", function () {
                                    $scope.cancel();
                                    $scope.findByConditions();
                                });
                            }else{
                                bootbox.alert("删除失败(" + data.reason + ")");
                            }
                        }, $scope.requestError);
                    }
                }
            });
        } else {
            bootbox.alert({
                title: "提示信息",
                message: "禁止删除生效队列，请先将队列设置为失效"
            });
        }
    }

    /**
     * 用户队列生效
     * @param queue
     */
    $scope.onEnable = function(queue){
        usrQueueService.onEnable({
            action:'onEnable',
            id:queue.id
        },{},function(data) {
            if(data.state == 'SUCCESS'){
                bootbox.alert("操作成功",function(){
                    $scope.cancel();
                    $scope.findByCondition();
                });
            }else{
                bootbox.alert("操作失败(" + data.reason + ")");
            }
        }, $scope.requestError);
    }

    /**
     * 用户队列失效
     * @param queue
     */
    $scope.onDisable = function(queue){
        usrQueueService.onDisable({
            action:'onDisable',
            id:queue.id
        },{},function(data) {
            if(data.state == 'SUCCESS'){
                bootbox.alert("操作成功",function(){
                    $scope.cancel();
                    $scope.findByCondition();
                });
            }else{
                bootbox.alert("操作失败(" + data.reason + ")");
            }
        }, $scope.requestError);
    }

    /**
     * 比较用户队列
     */
    $scope.getSynQueue = function(){
        usrQueueService.getSynQueue({
            action : 'analyzeSyncQueue'
        },{},function(data) {
            $scope.newQueue =data.data.newQueue;
            $scope.diffQueue =data.data.diffQueue;
            $('#dialogSyncQueue').modal('show');
        }, $scope.requestError);
    }

    /**
     * 同步用户队列
     */
    $scope.synQueue = function(){
        var newQueueArray = new Array();
        var diffQueueArray = new Array();
        $('input[type="checkbox"][name="addQueueList"]:checked').each(function () {
            var name = $(this).parent().parent().find('td').eq(1).text();
            var type = $(this).parent().parent().find('td').eq(3).children().eq(0).val();
            var priority = $(this).parent().parent().find('td').eq(3).children().eq(1).val();
            var persistent = $(this).parent().parent().find('td').eq(3).children().eq(2).val();
            var maxDepth = $(this).parent().parent().find('td').eq(3).children().eq(3).val();
            var maxMsgLength = $(this).parent().parent().find('td').eq(3).children().eq(4).val();
            var retainInterval = $(this).parent().parent().find('td').eq(3).children().eq(5).val();
            var queue = {name:name,type:type,priority:priority,persistent:persistent,maxDepth:maxDepth,maxMsgLength:maxMsgLength,retainInterval:retainInterval};
            newQueueArray.push(queue);
        });
        $('input[type="checkbox"][name="updateQueueList"]:checked').each(function () {
            var name = $(this).parent().parent().find('td').eq(1).text();
            var type = $(this).parent().parent().find('td').eq(3).children().eq(0).val();
            var priority = $(this).parent().parent().find('td').eq(3).children().eq(1).val();
            var persistent = $(this).parent().parent().find('td').eq(3).children().eq(2).val();
            var maxDepth = $(this).parent().parent().find('td').eq(3).children().eq(3).val();
            var maxMsgLength = $(this).parent().parent().find('td').eq(3).children().eq(4).val();
            var retainInterval = $(this).parent().parent().find('td').eq(3).children().eq(5).val();
            var queue = {name:name,type:type,priority:priority,persistent:persistent,maxDepth:maxDepth,maxMsgLength:maxMsgLength,retainInterval:retainInterval};
            diffQueueArray.push(queue);
        });
        var newQueue = JSON.stringify(newQueueArray);
        var diffQueue = JSON.stringify(diffQueueArray);
        usrQueueService.synQueue({
            action : 'synQueue',
            newQueue : newQueue,
            diffQueue : diffQueue
        },{},function(data) {
            if (data.state == 'SUCCESS') {
                bootbox.alert("同步成功");
                $scope.cancel();
                $scope.findByConditions();
            } else {
                bootbox.alert("查询失败(" + data.reason + ")");
                $scope.cancel();
                $scope.findByConditions();
            }
        }, $scope.requestError);
    }

    /**
     * 取消用户队列新增/修改操作
     */
    $scope.cancel = function(){
        $('#dialogQueue').modal('hide');
        $('#dialogSyncQueue').modal('hide');
    };
});
